package com.wuxin.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wuxin.dto.ExcelDictDTO;
import com.wuxin.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: jinrongxiangmu
 * @ClassName ExcelDictDTO
 * @description: 监听类
 * @author: 李尧坤
 * @create: 2025−01-15 19:39
 * @Version 1.0
 **/

public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private static final int BATCH_COUNT = 5;

    List<ExcelDictDTO> list = new ArrayList<>();
    //@Autowired
    private DictMapper dictMapper;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {

        //每遍历一行数据都执行
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            //进行数据保存
            saveData();
            //清除之前保存的数据
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        //进行数据保存
        saveData();
    }

    private void saveData(){
        //批量添加
        dictMapper.insertBach(list);
    }
}
